package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description RoleServiceImpl
 * @Author luohai
 * @Date 2024-10-24
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;

    /**
     * 角色分页
     *
     * @param roleDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<RoleVo> findRoleVoPage(RoleDto roleDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<RoleVo> page = roleMapper.findRoleVoPage(roleDto);
        return PageResponse.of(page, RoleVo.class);
    }

    /**
     * 保存角色
     *
     * @param roleDto 角色DTO对象
     * @return RoleVo
     */
    @Override
    public Boolean createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insertSelective(role);
        return true;
    }

    private final RoleResourceMapper roleResourceMapper;

    /**
     * 根据角色查询选中的资源数据
     *
     * @param roleId
     * @return
     */
    @Override
    public Set<String> findCheckedResources(Long roleId) {
        return roleResourceMapper.findCheckedResources(roleId);
    }

    private final UserRoleMapper userRoleMapper;

    /**
     * 角色修改
     *
     * @param roleDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(RoleDto roleDto) {
        //1.roleDto转换为role对象
        Role role = BeanUtil.toBean(roleDto, Role.class);
        //2.调用mapper直接修改角色单表数据(解决编辑角色，启用或禁用)
        //2.1 判断是否操作为禁用
        if (SuperConstant.DATA_STATE_1.equals(role.getDataState())) {
            //2.2.1 获取角色分配用户的数量
            Integer count = userRoleMapper.findCountByRoleId(role.getId());
            //2.2.2 数量大于0，抛出异常，该角色关联用户不可以禁用
            if (count > 0) {
                throw new RuntimeException("该角色关联用户不可以禁用");
            }
        }
        //2.2 直接修改
        roleMapper.updateByPrimaryKeySelective(role);
        //3.判断用户是否传递了分配资源编号集合数据（如果有关联的资源编号说明前端是点击菜单权限分配保存按钮）
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        if (checkedResourceNos != null && checkedResourceNos.length > 0) {
            //3.1 不为null并且数组长度大于0，先删除角色关联的资源中间表数据
            roleResourceMapper.deleteByRoleId(role.getId());
            //3.2 封装构建中间表集合数据List<RoleResource>
            List<RoleResource> roleResourceList = Arrays.stream(checkedResourceNos).map(resourceNo -> {return RoleResource.builder().roleId(role.getId()).resourceNo(resourceNo).dataState(SuperConstant.DATA_STATE_0).build();
            }).collect(Collectors.toList());
            //3.3 将中间表集合数据List<RoleResource>批量插入中间表中
            roleResourceMapper.batchInsert(roleResourceList);
        } else if (checkedResourceNos != null) {
            //4.不为null并且数组长度等于0，抛出异常，提示用户请勾选分配的资源
            throw new RuntimeException("请勾选分配的资源");
        }

    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Long roleId) {
        roleMapper.deleteByPrimaryKey(roleId);

        roleResourceMapper.deleteByRoleId(roleId);

        userRoleMapper.deleteByRoleId(roleId);
    }

    /**
     * 角色下拉框
     * @return
     */
    @Override
    public List<RoleVo> roleDropdownMenu() {
        return roleMapper.roleDropdownMenu();
    }
}
